package cn.xinyangtong.manager.service.impl;

import cn.xinyangtong.common.pojo.DefaultResult;
import cn.xinyangtong.manager.entity.Status;
import cn.xinyangtong.manager.entity.TreeNode;
import cn.xinyangtong.manager.service.ContentCategoryService;
import cn.xinyangtong.mapper.TbContentCategoryMapper;
import cn.xinyangtong.pojo.TbContentCategory;
import cn.xinyangtong.pojo.TbContentCategoryExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 内容分类管理
 * Created by fengbo on 2017/6/17.
 */
@Service("contentCategoryService")
public class ContentCategoryServiceImpl implements ContentCategoryService {

    @Autowired
    private TbContentCategoryMapper contentCategoryMapper;

    private final Logger log = LoggerFactory.getLogger(ContentCategoryServiceImpl.class);

    //查看分类列表
    @Override
    public List<TreeNode> getCategoryList(Long parentId) {
        //根据parentID查询节点列表
        TbContentCategoryExample example = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        criteria.andStatusEqualTo((int) Status.NORMAL.getStatus());
        List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
        List<TreeNode> result = new ArrayList<>();
        for (TbContentCategory cate : list) {
            //创建一个节点
            TreeNode node = new TreeNode(cate.getId(), cate.getName(), cate.getIsParent()?"closed":"open");
            result.add(node);
        }
        return result;
    }

    //添加内容分类
    @Transactional
    @Override
    public DefaultResult insertContentCategory(Long parentId, String name) {
        //创建一个pojo
        TbContentCategory contentCategory = new TbContentCategory();
        contentCategory.setName(name);
        contentCategory.setIsParent(false);
        //'状态。可选值:1(正常),2(删除)',
        contentCategory.setStatus((int) Status.NORMAL.getStatus());
        contentCategory.setParentId(parentId);
        contentCategory.setSortOrder(1);
        Date date = new Date();
        contentCategory.setCreated(date);
        contentCategory.setUpdated(date);
        TbContentCategory parentCat = contentCategoryMapper.selectByPrimaryKey(parentId);
        try {
            //添加记录
            int num = contentCategoryMapper.insert(contentCategory);
            if (num <= 0) {
                throw new RuntimeException();
            }
            //判断是否为true
            if (!parentCat.getIsParent()) {
                updateIsParent(parentCat, true);
            }
            //返回结果
            return DefaultResult.ok(contentCategory);
        } catch (Exception e) {
            log.warn("Insert Content Category Fail! ContentCategoryName = " + contentCategory.getName());
            throw new RuntimeException();
        }
    }

    //根据内容分类ID修改内容分类
    @Override
    public DefaultResult updateContentCategoryById(TbContentCategory contentCategory) {
        contentCategory.setUpdated(new Date());
        int num = contentCategoryMapper.updateByPrimaryKeySelective(contentCategory);
        if (num <= 0) {
            log.warn("Update Content Category By ID Fail! ContentCatehoryId = " + contentCategory.getId());
            return DefaultResult.error();
        }
        return DefaultResult.ok();
    }

    //删除内容分类
    @Transactional
    @Override
    public DefaultResult deleteContentCategory(Long id) {
        TbContentCategory contentCategory = contentCategoryMapper.selectByPrimaryKey(id);
        contentCategory.setStatus((int) Status.DELETE.getStatus());
        Date date = new Date();
        contentCategory.setUpdated(date);

        //查询count的条件
        TbContentCategoryExample example = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(contentCategory.getParentId());
        criteria.andStatusEqualTo((int) Status.NORMAL.getStatus());

        TbContentCategory parentCat = contentCategoryMapper.selectByPrimaryKey(contentCategory.getParentId());
        try {
            //删除该分类的子分类
            deleteChildContentCat(contentCategory.getId());

            //删除该分类
            DefaultResult result = updateContentCategoryById(contentCategory);
            if (result.getStatus() != 200) {
                throw new RuntimeException();
            }

            //修改父分类是否为父分类
            //判断是否为true
            int count = contentCategoryMapper.countByExample(example);
            if (count == 0 && parentCat.getIsParent()) {
                updateIsParent(parentCat, false);
            }
            return result;
        } catch (Exception e) {
            log.warn("Delete Content Category Fail! ContentCategoryId = " + contentCategory.getId() +
            ";Fail Message = " + e.getMessage());
            throw new RuntimeException();
        }
    }

    /***
     * 更改元素是否为父节点
     * @param parentCat
     * @param isParent
     */
    private void updateIsParent(TbContentCategory parentCat, boolean isParent) {
        Date date = new Date();
        parentCat.setIsParent(isParent);
        parentCat.setUpdated(date);
        //更新父节点
        DefaultResult result = updateContentCategoryById(parentCat);
        if (result.getStatus() != 200) {
            throw new RuntimeException();
        }
    }

    /***
     * 递归删除内容分类
     */
    private void deleteChildContentCat(Long parentId) {
        TbContentCategoryExample example = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);

        List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
        for (TbContentCategory contentCategory : list) {
            if (contentCategory.getIsParent()) {
                deleteChildContentCat(contentCategory.getId());
            }
            contentCategory.setUpdated(new Date());
            contentCategory.setStatus((int) Status.DELETE.getStatus());
            DefaultResult result = updateContentCategoryById(contentCategory);
            if (result.getStatus() != 200) {
                throw new RuntimeException();
            }
        }
    }
}
